import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;

import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.PrettyXmlSerializer;
import org.htmlcleaner.TagNode;


public class ClassSearchPage {
	private TagNode tagNode;
	public ClassSearchPage() throws MalformedURLException, IOException{
		CleanerProperties props = new CleanerProperties();
		 
		// set some properties to non-default values
		props.setTranslateSpecialEntities(true);
		props.setTransResCharsToNCR(true);
		props.setOmitComments(true);
		
		
		
		tagNode = new HtmlCleaner(props).clean(
			    new URL("http://classes.iastate.edu/")
		);
		

		new PrettyXmlSerializer(props).writeToFile(
			    tagNode, "testBanana.xml", "utf-8"
			);
	}
	
	public ArrayList<String> getDepartmentNames(){
		ArrayList<String> departmentNames = new ArrayList<String>();
		TagNode formtable = findTagNodeForName(tagNode, "select", "name",
				"dept");
		for(TagNode node : formtable.getChildTags()){
			
			departmentNames.add(node.getAttributeByName("value"));
			
		}
		departmentNames.remove(0);
		for(String a :departmentNames){
			System.out.println("dept name: " + a);
		}
	
		return departmentNames;
		
	}
	public ArrayList<String> getTerm()
	{
		ArrayList<String> term = new ArrayList<String>();
	
		TagNode form = findTagNodeForName(tagNode, "select", "name", "term");
		for(TagNode node: form.getChildTags()){
			term.add(node.getAttributeByName("value"));
		}
		for(String a :term){
			System.out.println("term name: " + a);
		}
		return term;
	}
	public static TagNode findTagNodeForName(TagNode node,String name,String attribute_name, String attribute_value){
			if(node.getName() != null && node.getName().equals(name)){
			//	System.out.println("Looking into attributes for :" + node.getName());
				Map<String,String> attributes = node.getAttributes();
				Set<String> keySet = attributes.keySet();
		
				for(String key: keySet){
					if(key.equals(attribute_name) && attributes.get(key).equals(attribute_value)){
						return node;
					}
				}
			}
	
			TagNode[] tags = node.getChildTags();
			for(TagNode tag:tags){
				TagNode newTag = findTagNodeForName(tag,name,attribute_name, attribute_value);
				if(newTag != null){
					return newTag;
				}
			}
		return null;

	}
	public static TagNode getChildByNumber(TagNode parent,int number){
		TagNode[] childTags = parent.getChildTags();
		return childTags[number];

	}
	
}
